package com.yangtu.nearbyshop.db.service;

import com.yangtu.nearbyshop.db.dao.NearbyshopOrderMapper2;
import com.yangtu.nearbyshop.db.domain.*;
import com.yangtu.nearbyshop.db.dao.NearbyshopOrderRefundMapper;
import com.yangtu.nearbyshop.db.service.itf.INearbyshopOrderRefundService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yangtu.nearbyshop.db.util.OrderUtil;
import com.yangtu.nearbyshop.db.vo.OrderRefundVo;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 退款表 服务实现类
 * </p>
 *
 * @author wanglei
 * @since 2019-09-14
 */
@Service
public class NearbyshopOrderRefundServiceImpl extends ServiceImpl<NearbyshopOrderRefundMapper,
        NearbyshopOrderRefund> implements INearbyshopOrderRefundService {

    @Autowired
    NearbyshopOrderMapper2 orderMapper2;

    @Autowired
    NearbyshopOrderRefundMapper refundMapper;

    @Autowired
    NearbyshopOrderGoodsService orderGoodsService;



    @Override
    public void refundApply(NearbyshopOrderRefund refund) {
        NearbyshopOrder2 order = orderMapper2.selectById(refund.getOrderId());
        BeanUtils.copyProperties(order,refund);
        refund.setOrderId(order.getId());
        refund.setId(null);
        refund.setApplyTime(new Date());
        refund.setHandleTime(new Date());
        refund.setRefundPrice(order.getActualPrice());
        refund.setRefundStatus(1);
        if(StringUtils.isEmpty(refund.getRefundReason())){
            refund.setRefundReason("后台记录退款");
        }
        refund.setRefundBy("2");

        //设置退款商品数量
        int gnum = 0;
        int i = 1;
        List<NearbyshopOrderGoods> goodsList = orderGoodsService.queryByOid(order.getId());
        for(NearbyshopOrderGoods og : goodsList){
            gnum += og.getNumber();
        }
        refund.setGoodsNum(gnum);
        refundMapper.insert(refund);

        NearbyshopOrder2 orderUpdate = new NearbyshopOrder2();
        orderUpdate.setId(order.getId());
        orderUpdate.setOrderStatus(OrderUtil.STATUS_REFUND_CONFIRM.intValue());
        orderMapper2.updateById(orderUpdate);


    }

    @Override
    public OrderRefundVo countRefund(Integer userId, Integer orderStatus, Integer orderId, String refundBy, String startTm, String endTm) {
        return refundMapper.countRefund(userId,orderStatus,orderId,refundBy,startTm,endTm);
    }
}
